package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


/**
 * ClassName:SubjectExcelListener
 * Package:com.atguigu.eduservice.listener
 * Description:
 *
 * @Date:2021/1/10 9:50
 * @Author:hm
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData>{

    //因为SubjectExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象
    //不能实现数据库操作
    public EduSubjectService subjectService;
    public SubjectExcelListener() {}
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }


    //一行一行读取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null) {
            throw new GuliException(20001,"文件数据为空");
        }

        //判断一级分类是否重复
        String title = subjectData.getOneSubjectName();
        EduSubject oneSubject = this.getOneSubject(subjectService, title);
        if (oneSubject==null){//不重复
            //向数据库添加
           oneSubject = new EduSubject();
           oneSubject.setTitle(title);
           subjectService.save(oneSubject);

        }
        //判断二级分类是否重复
        String twoSubjectName = subjectData.getTwoSubjectName();
        String pid = oneSubject.getId();
        EduSubject twoSubject = this.getTwoSubject(subjectService,twoSubjectName,pid);
        if (twoSubject==null){//不重复
            //向数据库添加
            twoSubject = new EduSubject();
            twoSubject.setTitle(twoSubjectName);
            twoSubject.setParentId(pid);
            subjectService.save(twoSubject);

        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {


    }

    //获取数据库一级分类
    private EduSubject getOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();

        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject eduSubject = subjectService.getOne(wrapper);
        return eduSubject;
    }
    //获取数据库二级分类
    private EduSubject getTwoSubject(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();

        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject eduSubject = subjectService.getOne(wrapper);
        return eduSubject;
    }
}
